import { Component, OnInit } from '@angular/core';
import {Role} from "../role";
import {Router, ActivatedRoute} from "@angular/router";
import {LogUtil} from "../../../../util/log-util";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {RolesService} from "../roles.service";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Dialog} from "../../../../widgets/one-dialog/dialog";
import {MsgResult} from "../../../../models/msg-result";
import {Validators, FormGroup, FormBuilder} from "@angular/forms";
import {MsgConstants} from "../../../../constants/constants";

@Component({
  selector: 'app-role-update',
  templateUrl: './role-update.component.html'
})
export class RoleUpdateComponent implements OnInit {

  /**
   * 声明对象
   */
  role :Role;
  /**
   * 定义变量id
   */
  id:string;

  roleForm : FormGroup;

  constructor(
    private router : Router,
    private route : ActivatedRoute,
    private logUtil : LogUtil,
    private fb: FormBuilder,
    private pageSubject : PageSubject,
    private dialogService : OneDialogService,
    private responseUtil : ResponseUtil,
    private rolesService : RolesService
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    //获取路径参数
    if (!!this.route.snapshot.params["roleId"]) {
      this.id = this.route.snapshot.params["roleId"];
      //初始化表单
      this.initRoleUpdateForm(this.id);
    }

  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("角色管理", "修改", path);
  }

  /**
   * 初始化修改表单
   * @param id
   */
  initRoleUpdateForm(id) {
    this.rolesService.getRoleById(id).subscribe(
      result => this.responseUtil.success(result, this.processRoleByIdResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *
   * @param result
   */
  private processRoleByIdResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.role = result.data;
      this.roleForm.patchValue(this.role);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }


  /**
   * 构造表单
   */
  buildForm(): void {
    this.roleForm = this.fb.group({
      'roleId': [this.role.roleId],
      'roleName': [this.role.roleName, [
        Validators.required,
        Validators.maxLength(30)
      ]],
      'description': [this.role.description, [
        Validators.maxLength(50),
      ]]
    });

    this.roleForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.roleForm) {
      return;
    }
    const form = this.roleForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'roleName': '',
    'description': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'roleName': {
      'required': '角色名不能为空',
      'maxlength': '长度不能超过30',
    },
    'description': {
      'maxlength': '长度不能超过50'
    }
  };


  /**
   * 实现修改
   */
  onSubmit() {
    this.role = this.roleForm.value;
    this.rolesService.updateRole(this.role).subscribe(
      result => this.responseUtil.success(result, this.processRoleUpdateResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 获取修改日志
   * @param result
   */
  private processRoleUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.cancelRoleUpdate();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消修改
   */
  cancelRoleUpdate() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.role = new Role("", "", "", "", "", "", "");
    this.buildForm();
  }

}
